package myDuoXianChen;

/**
 * Description:
 * Author:    Dane
 * CreateTime:2024/10/19-上午11:25
 * Since  :   1.0
 * Version:   1.0
 */
import java.util.concurrent.locks.ReentrantLock;

class BankAccount {
    private double balance;
    private final ReentrantLock lock = new ReentrantLock();

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }




    public void deposit(double amount) {
//        lock.lock();
//        try {
//            System.out.println("存款前余额: " + balance);
//            balance += amount;
//            System.out.println("存款后余额: " + balance);
//        } finally {
//            lock.unlock();
//        }

        lock.lock();
     try {
         System.out.println("存款前余额 "+balance);
         balance+=amount;
         System.out.println("存款后余额");
     }finally {
         lock.unlock();
     }
    }

    public void withdraw(double amount) {
//        lock.lock();
//        try {
//            System.out.println("取款前余额: " + balance);
//            if (balance >= amount) {
//                balance -= amount;
//                System.out.println("取款后余额: " + balance);
//            } else {
//                System.out.println("余额不足");
//            }
//        } finally {
//            lock.unlock();
//        }
        lock.lock();
        try {
            System.out.println("取款前余额 "+balance);
            if (balance>=amount) {
                balance-=amount;
                System.out.println("取款后余额 "+balance);
            }else {
                System.out.println("余额不足");
            }

        }finally {
            lock.unlock();
        }


    }

    public double getBalance() {
        lock.lock(); // 获取锁
        try {
            return balance;
        } finally {
            lock.unlock(); // 确保释放锁
        }
    }
}

public class BankExample {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(1000.0);

        // 创建多个线程进行转账操作
        Thread t1 = new Thread(() -> {
            account.deposit(500);

        });

        Thread t2 = new Thread(() -> {
            account.withdraw(300);

        });

        Thread t3 = new Thread(() -> {
            account.withdraw(8000);

        });

        // 启动线程
        t1.start();
        t2.start();
        t3.start();

        // 等待线程完成
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终余额: " + account.getBalance());
    }
}
